interface TimeFormat {
  dateDiff(start: any, end: any): number;
  getTimeLimit(count: number): {
    y: number;
    M: string | number;
    d: number;
    h: string | number;
    m: string | number;
    s: string | number;
  };
  format(day: Date | string, fmt: string): string;
  parseDate(time: Date, type: string): string;
}
export const concatO = (t: number) => {
  if (t < 10) {
    return '0' + t;
  }
  return t.toString();
};

const timeFormat: TimeFormat = {
  parseDate(date: Date, type?: string) {
    const year = date.getFullYear().toString(),
      month = concatO(date.getMonth() + 1),
      day = concatO(date.getDate()),
      hour = concatO(date.getHours()),
      min = concatO(date.getMinutes()),
      seconds = concatO(date.getSeconds());
    if (type == '/') return `${year}/${month}/${day} ${hour}:${min}`;
    if (type == '.') return `${year}.${month}.${day} ${hour}:${min}`;
    if (type == 'chinese')
      return `${year}年${month}月${day}日 ${hour}:${min}:${seconds}`;
    return `${year}-${month}-${day} ${hour}:${min}`;
  },
  dateDiff(start, end) {
    const [startDate, endDate] = [
      new Date(
        typeof start === 'string' ? start.toString().replace(/-/g, '/') : start
      ),
      new Date(
        typeof end === 'string' ? end.toString().replace(/-/g, '/') : end
      ),
    ];
    let ms = endDate.getTime() - startDate.getTime();
    if (ms < 0) {
      ms = 0;
    }
    return ms;
  },
  getTimeLimit(count) {
    const [y, M, d, h, m, s] = [
      Math.floor(count / 1000 / 60 / 60 / 24 / 365),
      Math.floor((count / 1000 / 60 / 60 / 24 / 31) % 12),
      Math.floor((count / 1000 / 60 / 60 / 24) % 31),
      Math.floor((count / 1000 / 60 / 60) % 24),
      Math.floor((count / 1000 / 60) % 60),
      Math.floor((count / 1000) % 60),
    ];
    return {
      y: y,
      M: M < 10 ? `0${M}` : M,
      d: d,
      h: h < 10 ? `0${h}` : h,
      m: m < 10 ? `0${m}` : m,
      s: s < 10 ? `0${s}` : s,
    };
  },
  format(day = new Date(), fmt) {
    if (typeof day === 'string') {
      day = new Date(day.replace(/-/g, '/'));
    }
    const o: {
      [key: string]: number;
    } = {
      'M+': day.getMonth() + 1, // 月份
      'd+': day.getDate(), // 日
      'h+': day.getHours(), // 小时
      'm+': day.getMinutes(), // 分
      's+': day.getSeconds(), // 秒
      'q+': Math.floor((day.getMonth() + 3) / 3), // 季度
      S: day.getMilliseconds(), // 毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (day.getFullYear() + '').substr(4 - RegExp.$1.length)
      );
    }
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k].toString()
            : ('00' + o[k]).substr(('' + o[k]).length)
        );
      }
    }
    return fmt;
  },
};

export default timeFormat;
